﻿using AutoMapper;
using MediatR;
using ProductionManagement.Application.Command.MaterialCommand;
using ProductionManagement.Domain.ProductionDomain;
using ProductionManagement.Infrstructre.lnterface;
using SqlSugar;

namespace ProductionManagement.Application.CommandHandler.MaterialCommandHandlers
{
    public class MaterialDelCommandHandlers : IRequestHandler<MaterialDelCommand, int>
    {
        private readonly IMaterialRepository _materialRepository;
        private readonly IItemSubpiecesRepository _itemSubpiecesRepository;
        private readonly ISqlSugarClient db;
        private readonly IMapper mapper;
        public MaterialDelCommandHandlers(IMaterialRepository materialRepository, IItemSubpiecesRepository itemSubpiecesRepository, IMapper mapper, ISqlSugarClient db)
        {
            _materialRepository = materialRepository;
            _itemSubpiecesRepository = itemSubpiecesRepository;
            this.mapper = mapper;
            this.db = db;
        }


        public async Task<int> Handle(MaterialDelCommand request, CancellationToken cancellationToken)
        {
            // 开启事务
            db.Ado.BeginTran();
            try
            {
                var list = (await _materialRepository.GetAll()).Where(x => request.MaterialId.Contains(x.MaterialId)).ToList();
                 foreach (var material in list)
                {
                    material.IsDel=true;
                    material.DelName=request.DelName;
                    material.DelTime=DateTime.Now;
                    var item=(await _itemSubpiecesRepository.GetAll()).Where(x => x.MaterialNode==material.MaterialNode).ToList();
                    foreach (var subpiece in item)
                    {
                        subpiece.IsDel=true;
                        subpiece.DelName=request.DelName;
                        subpiece.DelTime = DateTime.Now;
                        await _itemSubpiecesRepository.UpdAsync(subpiece);
                    }
                    await _materialRepository.UpdAsync(material);
                }
                db.Ado.CommitTran();
            }
            catch (Exception ex)
            {
                db.Ado.RollbackTran();
                throw ex;
            }
            finally
            {
                db.Ado.Close();
            }
            return 1;
        }
                
    }
}
